package com.cuts.videoedit

import android.graphics.ImageDecoder
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.cuts.videoedit.bean.PacketBean
import com.cuts.videoedit.data.YUVDataBean
import com.cuts.videoedit.databinding.ActivityMainBinding
import com.cuts.videoedit.helper.IFFmpegCodecFrameHelper
import com.cuts.videoedit.util.PlayerStatus
import com.cuts.videoedit.util.PlayerStatus.PREPARE
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.shen.show.GetFrameListener
import com.shen.show.NativeLib
import com.shen.show.PlayerListener
import java.io.File

class MainActivity : AppCompatActivity() {

    private  val TAG = "MainActivity"

    private lateinit var binding: ActivityMainBinding

//    var mVideoFrameRecyclerView:VideoFrameRecyclerView?=null;

    var mNativeLib:NativeLib?=null

    fun initView(){
        val file= File(path);
        if (file.exists()){
            Log.e(TAG,"exist")
        }
        mNativeLib=NativeLib()
       mNativeLib?.setPath(path)
//        mNativeLib?.prepare()
//
//        mNativeLib?.mPlayerListener=object :PlayerListener{
//            override fun onStatus(status: Int) {
//                Log.i(TAG, "onStatus$status")
//                when(status){
//                    PREPARE->{
//                        mNativeLib?.start()
//                    }
//
//                    PlayerStatus.GETFRAME->{
//                        mNativeLib?.start()
////                      mNativeLib?.n_start_by_ffmpeg();
//                    }
//                }
//            }
//
//            override fun onGetFrameYUV(
//                width: Int,
//                height: Int,
//                y: ByteArray,
//                u: ByteArray,
//                v: ByteArray,
//                practicalWidth: Int,
//                timeUs: Double
//            ) {
//                TODO("Not yet implemented")
//            }
//
//            override fun onSizeChange(width: Int, height: Int) {
//                Log.e(TAG, "onSizeChange $width $height")
//
//                binding.playView.post {
//                    binding.playView.setAspectRatio(width,height);
//                }
//            }
//        }

        val avFrameHelper = IFFmpegCodecFrameHelper(path,0)

        binding.previewFrame.setAvFrameHelper(avFrameHelper)

        mNativeLib?.initGetFrame(path)

        mNativeLib?.mGetFrameListener=object :GetFrameListener{
            override fun onInited(
                codecName: String?,
                width: Int,
                height: Int,
                csd_0: ByteArray?,
                csd_1: ByteArray?
            ) {
                Log.e(TAG,"onInited")
                mNativeLib?.startGetFrame()
                mNativeLib?.mGetFrameListener?.onStarGetFrame()
            }

            override fun onStarGetFrame() {
                runOnUiThread {
                    binding.previewFrame.adapter?.notifyDataSetChanged()
                }
            }

            override fun getFramePacket(dataSize: Int, pts: Double, data: ByteArray?) {
                val packetBean = PacketBean()
                packetBean.data = data
                packetBean.pts = pts
                packetBean.dataSize = dataSize
            }

            override fun onGetFrameYUV(
                width: Int,
                height: Int,
                y: ByteArray?,
                u: ByteArray?,
                v: ByteArray?,
                practicalWidth: Int,
                timeUs: Double
            ) {
                runOnUiThread {
                    val bean = YUVDataBean()
                    bean.width = width
                    bean.height = height
                    bean.y = y
                    bean.u = u
                    bean.v = v
                    bean.practicalWidth = practicalWidth
                    bean.timeUs = timeUs.toLong()
                    Log.e(TAG,"add frame"+(binding.previewFrame.getAvFrameHelper() as IFFmpegCodecFrameHelper).yuvQueue.getQueueSize())
                    (binding.previewFrame.getAvFrameHelper() as IFFmpegCodecFrameHelper).yuvQueue.enQueue(bean)
//                    binding.previewFrame.mIAvFrameHelper
//                     binding.previewFrame.setYUVData(bean)

                }
            }

            override fun onGetFrameYUV2(
                width: Int,
                height: Int,
                yuv: ByteArray?,
                practicalWidth: Int,
                timeUs: Double
            ) {

            }

        }
    }


    var path="/sdcard/midway.mp4"

//    var path="/storage/emulated/0/avier1.mp4"
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.root.postDelayed({initView()},3000)


    XXPermissions.with(this)
            // 申请单个权限


            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            // 申请多个权限

            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            //.unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
//                        toast("获取部分权限成功，但部分权限未正常授予")
                        return
                    }


//                    toast("获取录音和日历权限成功")
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
//                        toast("被永久拒绝授权，请手动授予录音和日历权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@MainActivity, permissions)
                    } else {
//                        toast("获取录音和日历权限失败")
                    }
                }
            })

    }

}